/*
 * Copyright 2010 Biz-e (info@biz-e.nl)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.biz_e.gwt.baselib.ui.client.util;

import java.util.List;
import java.util.Vector;

import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Node;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.user.client.ui.Widget;

/**
 * Some utility functions to handle common tasks for {@link Widget}s, DOM
 * {@link Element}s etcetera.
 * 
 * @author Joost A. Bloemsma
 */
public class UiUtils {
    /**
     * Removes all child elements from an {@link Element}
     * 
     * @param element
     */
    public static void removeChildren(Element element) {
        NodeList<Node> list = element.getChildNodes();
        while (list.getLength() > 0) {
            element.removeChild(list.getItem(0));
        }
        return;
    }

    /**
     * Removes all child elements from an {@link UIObject}
     * 
     * @param ui
     */
    public static void removeChildren(UIObject ui) {
        removeChildren(ui.getElement());
        return;
    }

    /**
     * Creates a {@link List} of childnodes of the passed {@link Element}.
     * Unlike the {@link NodeList} returned by {@link Element#getChildNodes()},
     * the {@link List} returned
     * by this method is a standard, iterable List.<br/>
     * <p>
     * Note:<br/>
     * Where the {@link NodeList} is a <i>live</i> view to the DOM of the
     * element, this {@link List} is not. That means that once the {@link List}
     * is created, it will not be updated when the underlying DOM is modified,
     * whereas the {@link NodeList} will be.
     * 
     * @param element
     * @return A {@link List} of {@link Node}s
     */
    public static List<Node> getChildNodesAsList(Element element) {
        List<Node> nodes = new Vector<Node>();
        NodeList<Node> list = element.getChildNodes();
        int count = list.getLength();
        for (int i = 0; i < count; i++) {
            nodes.add(list.getItem(i));
        }
        return nodes;
    }

    /**
     * Sets the child as the <u>only</u> child element of the parent.
     * 
     * @param parent
     * @param child
     */
    public static void setChildElement(Element parent, Element child) {
        removeChildren(parent);
        parent.appendChild(child);
    }
}
